package cn.tedu.baking.service.impl;

import cn.tedu.baking.mapper.CommentMapper;
import cn.tedu.baking.mapper.ContentMapper;
import cn.tedu.baking.pojo.dto.ContentDTO;
import cn.tedu.baking.pojo.entity.Content;
import cn.tedu.baking.pojo.vo.*;
import cn.tedu.baking.service.IContentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;

@Service
public class ContentService implements IContentService {
    @Autowired
    ContentMapper mapper;
    @Override
    public void addNew(ContentDTO contentDTO) {
        Content content = new Content();
        BeanUtils.copyProperties(contentDTO,content);
        if(contentDTO.getId()==null){//发布
            content.setCreateTime(new Date());
            mapper.insert(content);
        }else {//修改
            content.setUpdateTime(new Date());//设置修改时间
            mapper.update(content);
        }
    }

    @Override
    public List<ContentManagementVO> listForManagement(Long type, Long userId) {
        return mapper.selectForManagementByTypeAndUserId(type,userId);
    }
    @Autowired
    CommentMapper commentMapper;
    @Value("${file-path}")
    private String dirPath;
    @Override
    public void deleteById(Long id) {
        //删除图片和视频文件
        ContentDetailVO contentDetailVO = mapper.selectDetailById(id);
        //删除图片
        new File(dirPath+contentDetailVO.getImgUrl()).delete();
        if(contentDetailVO.getType()==5){
            //删除视频
            new File(dirPath+contentDetailVO.getVideoUrl()).delete();
        }
        //通过内容ID删除和此内容相关的评论
        commentMapper.deleteByContentId(id);
        //删除数据库中的数据
        mapper.deleteById(id);
    }

    @Override
    public ContentUpdateVO selectForUpdateById(Long id) {
        return mapper.selectForUpdateById(id);
    }

    @Override
    public List<ContentIndexVO> listForIndexByTypeAndCategoryId(Long type, Long categoryId) {
        return mapper.selectForIndexByTypeAndCategoryId(type,categoryId);
    }

    @Override
    public ContentDetailVO detailById(Long id) {
        //让浏览量加一
        mapper.updateViewCountById(id);
        return mapper.selectDetailById(id);
    }

    @Override
    public List<ContentSimpleVO> otherByUserId(Long id) {
        return mapper.selectOtherByUserId(id);
    }

    @Override
    public List<ContentSimpleVO> hotList() {
        return mapper.selectHot();
    }

    @Override
    public List<ContentIndexVO> listByType(Long type) {

        return mapper.selectListByType(type);
    }

    @Override
    public List<ContentIndexVO> searchByWd(String wd) {
        return mapper.selectByWd(wd);
    }

    @Override
    public List<ContentAdminVO> listForAdmin(Long type) {
        return mapper.selectContentByType(type);
    }
}
